<?php

namespace app\admin\controller\kmh;

use app\admin\model\VoucherAccount;
use app\common\controller\Backend;
use app\common\library\WechatPay;
use app\common\model\NewVoucher;
use app\admin\model\User;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use think\Db;
use think\Exception;
use think\Log;

/**
 * 代金券
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{
    
    /**
     * Order模型对象
     * @var \app\admin\model\kmh\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\kmh\Order;

    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->where('status','<>',1)
                ->with(['voucher','business','staff'])
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if($params['number'] != $row['number']){
                        if($params['number'] < $row['number']){
                            $number = bcsub($row['number'], $params['number']);
                            VoucherAccount::where(['branch_id'=>$row->branch_id,'voucher_id'=>$row->voucher_id,'admin_id'=>$row->admin_id])->setDec('send_number',$number);
                        }else{
                            $number = bcsub($params['number'],$row['number']);
                            //判断是否有库存
                            $acount = VoucherAccount::where(['branch_id'=>$row->branch_id,'voucher_id'=>$row->voucher_id,'admin_id'=>$row->admin_id])->find();
                            if($acount){
                                $sy = bcsub($acount['total_number'],$acount['send_number']);
                                if($sy < $number)
                                {
                                    Db::rollback();
                                    $this->error('库存不足');
                                }
                                
                                VoucherAccount::where(['branch_id'=>$row->branch_id,'voucher_id'=>$row->voucher_id,'admin_id'=>$row->admin_id])->setInc('send_number',$number);
                            }else{
                                Db::rollback();
                                $this->error('未查询到库存信息');
                            }

                        }
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    if($v->type != 2){
                        Db::rollback();
                        $this->error('非实物商品不能删除');
                    }
                    VoucherAccount::where(['branch_id'=>$v->branch_id,'voucher_id'=>$v->voucher_id,'admin_id'=>$v->admin_id])->setDec('send_number',$v->number);
                    $count += $v->delete();
                    
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    /**
     * 导出Excel方法
     */
    public function export()
    {
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $this->model
            ->where($where)
            ->where('status','<>',1)
            ->with(['voucher','staff'])
            ->order($sort, $order);
        # 判断是否获取指定数据
        if (!empty($this->request->get('id_data'))) {
            $id_data = explode(',',$this->request->get('id_data'));
            $this->model->where(['id'=>['IN',$id_data]]);
        }
        $list = $this->model->select();

        $list = collection($list)->toArray();
        $count = count($list); // 总条数
        if($count > 300){
            $this-error('导出数据不能超出300条');
        }
        # 填充表头数据
        $head = ['流水编号','礼品','金额','数量','支行','柜员号','客户姓名','客户手机号','业务金额','业务期限','业务','添加员工','时间','客户类型','凭证'];
        # 字母列表
        $letterList = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K','L','M','N','O'];
        # 找到当前脚本所在路径
        $path = dirname(__FILE__);
        # 实例化phpexcel
        $PHPExcel = new Spreadsheet();
        $PHPSheet = $PHPExcel->getActiveSheet();
        # 设置表内部名称
        $PHPSheet->setTitle("Sheet1");

        $PHPSheet->getColumnDimension('A')->setWidth(30);
        $PHPSheet->getColumnDimension('B')->setWidth(31);
        $PHPSheet->getColumnDimension('C')->setWidth(10);
        $PHPSheet->getColumnDimension('D')->setWidth(10);
        $PHPSheet->getColumnDimension('E')->setWidth(13);
        $PHPSheet->getColumnDimension('F')->setWidth(10);
        $PHPSheet->getColumnDimension('G')->setWidth(13);
        $PHPSheet->getColumnDimension('H')->setWidth(20);
        $PHPSheet->getColumnDimension('I')->setWidth(15);
        $PHPSheet->getColumnDimension('J')->setWidth(15);
        $PHPSheet->getColumnDimension('K')->setWidth(10);
        $PHPSheet->getColumnDimension('L')->setWidth(10);
        $PHPSheet->getColumnDimension('M')->setWidth(19);
        $PHPSheet->getColumnDimension('N')->setWidth(19);
        $PHPSheet->getColumnDimension('O')->setWidth(20);

        # 设置表格数据
        foreach ($head as $kk => $vv) {
            $PHPSheet->setCellValue($letterList[$kk]."1", $vv);
        }
        # 设置宽度
        /*$PHPSheet->getColumnDimension('A')->setWidth(20);
        $PHPSheet->getColumnDimension('B')->setWidth(12);
        $PHPSheet->getColumnDimension('B')->setWidth(20);*/
        # 设置高度
        for ($i = 2; $i <= $count+1 ; $i++) {
            $PHPSheet->getRowDimension($i)->setRowHeight(30);
        }
        $num = 2; // 从第二行开始插入
        # 数据填充
        foreach ($list as $k => $v) {
            $extend_name = $v['extend1'] == 1? '行内':'行外';
            $PHPSheet->setCellValueExplicit("A" . $num, $v['order_no'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $PHPSheet->setCellValue("B" . $num, $v['voucher_name']);
            $PHPSheet->setCellValue("C" . $num, $v['voucher']['money_hui']);
            $PHPSheet->setCellValue("D" . $num, $v['number']);
            $PHPSheet->setCellValue("E" . $num, $v['branch_name']);
            $PHPSheet->setCellValue("F" . $num, $v['gyh']);
            $PHPSheet->setCellValue("G" . $num, $v['user_name']);
            $PHPSheet->setCellValue("H" . $num, $v['user_phone']);
            $PHPSheet->setCellValue("I" . $num, $v['user_money']);
            $PHPSheet->setCellValue("J" . $num, $v['time_limit']);
            $PHPSheet->setCellValue("K" . $num, $v['business_name']);
            $PHPSheet->setCellValue("L" . $num, $v['staff']['name']);
            $PHPSheet->setCellValue("M" . $num, $v['createtime'] == 0 ? '' : date('Y-m-d H:i:s',$v['createtime']));
            $PHPSheet->setCellValue("N" . $num, $extend_name);
            // if($v['image']){
            //     $objDrawing  = new Drawing();
            //     // 获取图片地址
            //     $objDrawing->setPath('.'.$v['image']);
            //     // 设置图片存放在表格的位置
            //     $objDrawing->setCoordinates("O" . $num);
            //     // 设置表格宽度
            //     // $PHPSheet->getColumnDimension('N')->setWidth(20);
            //     // 设置表格高度
            //     $PHPSheet->getRowDimension($num)->setRowHeight(60);
            //     // 设置图片宽
            //     $objDrawing->setWidth(80);
            //     // 设置图片高
            //     $objDrawing->setHeight(60);
            //     // 设置图片水平居中
            //     $objDrawing->setOffsetX(20);
    
    
            //     $objDrawing->setWorksheet($PHPSheet);
            // }
            
            $num++;
        }
        # 文档名称
        $filename = date('YmdHis');
        # 创建生成的格式
        // $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel, "Excel2007");
        $PHPWriter = new Xlsx($PHPExcel);
        ob_end_clean();
        # 代入文档名称
        header("Content-Disposition: attachment;filename=$filename.xlsx");
        header("Content-Type: text/html;charset=utf-8");
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        # 生成文件
        $PHPWriter->save("php://output");
        exit();
    }


    public function send($ids)
    {
        // 检查订单状态
        $order = $this->model->where(['id' => $ids, 'status' => 0])->find();
        if (empty($order)) {
            $this->error('发放失败：未达到发放条件');
        }
        $voucher = NewVoucher::where('id', $order->voucher_id)->find();
        $user = User::where('id', $order->user_id)->find();
        $order_no = 'new' . time() . mt_rand(1000, 9999);
        // 发送优惠券
        $wechat_obj = new WechatPay(2);
        list($code, $data) = $wechat_obj->sendCoupon($voucher->stock_id, $order_no, $user->openid);
        // 记录日志
        Log::record([
            'code' => $code,
            'data' => $data,
            'order_id' => $ids
        ], '优惠券发放结果');
        if ($code != 1) {
            $this->error('发放失败');
        }
        try {
            // 更新订单状态
            $order->save([
                'status' => 2,
                'voucher_stock_id' => $voucher->stock_id,
                'user_coupon_id' => $data['coupon_id']
            ]);
            // 更新库存
            $voucher->setDec('sy_number', $order->number);
            $this->success('发放成功');
        } catch (Exception $e) {
            $this->error('发放失败:' . $e->getMessage());
        }
    }

}
